package org.example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.Timer;

public class SnakeGame extends JFrame {
    private static final int TILE_SIZE = 25;
    private static final int DEFAULT_WIDTH = 20;
    private static final int DEFAULT_HEIGHT = 15;

    private GamePanel gamePanel;
    private GameMenu gameMenu;
    private int gameWidth = DEFAULT_WIDTH;
    private int gameHeight = DEFAULT_HEIGHT;
    private int speed = 150; // 默认速度(毫秒)
    private boolean isPaused = false;
    private boolean gameStarted = false;
    private Font uiFont;

    public SnakeGame() {
        // 初始化字体
        initFonts();

        setTitle("贪吃蛇游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        gameMenu = new GameMenu(this);
        setJMenuBar(gameMenu);

        gamePanel = new GamePanel();
        add(gamePanel);

        pack();
        setLocationRelativeTo(null);
    }

    private void initFonts() {
        // 尝试加载几种常见字体，如果都失败则使用默认字体
        String[] fontNames = {"Microsoft YaHei", "SimSun", "Arial", "Dialog", "SansSerif"};
        Font font = null;

        for (String name : fontNames) {
            try {
                font = new Font(name, Font.PLAIN, 12);
                if (font.canDisplay('中') && font.canDisplay('A')) {
                    break;
                }
            } catch (Exception e) {
                // 如果字体不可用，继续尝试下一个
            }
        }

        if (font == null || !font.canDisplay('中')) {
            font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        }

        this.uiFont = font;

        // 设置全局UI字体
        setUIFont(font);
    }

    private static void setUIFont(Font font) {
        java.util.Enumeration<Object> keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            if (UIManager.get(key) instanceof Font) {
                UIManager.put(key, font);
            }
        }
    }

    public void startNewGame(int width, int height, int speed, boolean twoPlayers, int mapType) {
        this.gameWidth = width;
        this.gameHeight = height;
        this.speed = speed;
        this.gameStarted = true;
        this.isPaused = false;

        gamePanel.startNewGame(width, height, speed, twoPlayers, mapType);
        gamePanel.requestFocusInWindow();
    }

    public void togglePause() {
        if (gameStarted) {
            isPaused = !isPaused;
            gamePanel.setPaused(isPaused);
            if (isPaused) {
                JOptionPane.showMessageDialog(this, "游戏已暂停", "暂停", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    private class GamePanel extends JPanel implements ActionListener {
        private Timer timer;
        private Snake snake1;
        private Snake snake2;
        private Point food;
        private boolean gameOver = false;
        private boolean twoPlayers = false;
        private int[][] map;
        private int score1 = 0;
        private int score2 = 0;
        private Font panelFont;

        public GamePanel() {
            panelFont = uiFont.deriveFont(Font.PLAIN, 14);
            setFont(panelFont);

            setPreferredSize(new Dimension(DEFAULT_WIDTH * TILE_SIZE, DEFAULT_HEIGHT * TILE_SIZE));
            setBackground(new Color(30, 30, 30));
            setFocusable(true);

            addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if (gameOver) {
                        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                            startNewGame(gameWidth, gameHeight, speed, twoPlayers, getMapType());
                        }
                        return;
                    }

                    if (e.getKeyCode() == KeyEvent.VK_P) {
                        togglePause();
                        return;
                    }

                    if (isPaused) return;

                    // 玩家1控制 (WASD或方向键)
                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_UP:
                        case KeyEvent.VK_W:
                            if (snake1.getDirection() != Direction.DOWN) {
                                snake1.setDirection(Direction.UP);
                            }
                            break;
                        case KeyEvent.VK_DOWN:
                        case KeyEvent.VK_S:
                            if (snake1.getDirection() != Direction.UP) {
                                snake1.setDirection(Direction.DOWN);
                            }
                            break;
                        case KeyEvent.VK_LEFT:
                        case KeyEvent.VK_A:
                            if (snake1.getDirection() != Direction.RIGHT) {
                                snake1.setDirection(Direction.LEFT);
                            }
                            break;
                        case KeyEvent.VK_RIGHT:
                        case KeyEvent.VK_D:
                            if (snake1.getDirection() != Direction.LEFT) {
                                snake1.setDirection(Direction.RIGHT);
                            }
                            break;
                    }

                    // 玩家2控制 (IJKL)
                    if (twoPlayers) {
                        switch (e.getKeyCode()) {
                            case KeyEvent.VK_I:
                                if (snake2.getDirection() != Direction.DOWN) {
                                    snake2.setDirection(Direction.UP);
                                }
                                break;
                            case KeyEvent.VK_K:
                                if (snake2.getDirection() != Direction.UP) {
                                    snake2.setDirection(Direction.DOWN);
                                }
                                break;
                            case KeyEvent.VK_J:
                                if (snake2.getDirection() != Direction.RIGHT) {
                                    snake2.setDirection(Direction.LEFT);
                                }
                                break;
                            case KeyEvent.VK_L:
                                if (snake2.getDirection() != Direction.LEFT) {
                                    snake2.setDirection(Direction.RIGHT);
                                }
                                break;
                        }
                    }
                }
            });
        }

        public void startNewGame(int width, int height, int speed, boolean twoPlayers, int mapType) {
            this.twoPlayers = twoPlayers;
            this.gameOver = false;
            this.score1 = 0;
            this.score2 = 0;

            setPreferredSize(new Dimension(width * TILE_SIZE, height * TILE_SIZE));
            revalidate();

            // 初始化地图
            initializeMap(width, height, mapType);

            // 初始化蛇
            snake1 = new Snake(width / 4, height / 2, Direction.RIGHT);
            if (twoPlayers) {
                snake2 = new Snake(width * 3 / 4, height / 2, Direction.LEFT);
            } else {
                snake2 = null;
            }

            // 生成食物
            spawnFood();

            // 设置定时器
            if (timer != null) {
                timer.stop();
            }
            timer = new Timer(speed, this);
            timer.start();

            repaint();
        }

        private void initializeMap(int width, int height, int mapType) {
            map = new int[width][height];

            if (mapType == 1) { // 边框地图
                for (int x = 0; x < width; x++) {
                    map[x][0] = 1;
                    map[x][height - 1] = 1;
                }
                for (int y = 0; y < height; y++) {
                    map[0][y] = 1;
                    map[width - 1][y] = 1;
                }
            } else if (mapType == 2) { // 迷宫地图
                // 先设置边框
                for (int x = 0; x < width; x++) {
                    map[x][0] = 1;
                    map[x][height - 1] = 1;
                }
                for (int y = 0; y < height; y++) {
                    map[0][y] = 1;
                    map[width - 1][y] = 1;
                }

                // 添加一些障碍物
                int centerX = width / 2;
                int centerY = height / 2;

                for (int x = centerX - 2; x <= centerX + 2; x++) {
                    map[x][centerY - 3] = 1;
                    map[x][centerY + 3] = 1;
                }
                for (int y = centerY - 2; y <= centerY + 2; y++) {
                    map[centerX - 3][y] = 1;
                    map[centerX + 3][y] = 1;
                }
            }
            // mapType 0 是空白地图
        }

        private int getMapType() {
            if (map == null) return 0;

            boolean hasWalls = false;
            for (int x = 0; x < map.length; x++) {
                for (int y = 0; y < map[0].length; y++) {
                    if (map[x][y] == 1) {
                        hasWalls = true;
                        break;
                    }
                }
                if (hasWalls) break;
            }

            if (!hasWalls) return 0;

            // 简单判断是否是迷宫地图(有内部障碍物)
            int centerX = map.length / 2;
            int centerY = map[0].length / 2;
            if (map[centerX][centerY] == 1) {
                return 2;
            }

            return 1;
        }

        private void spawnFood() {
            Random random = new Random();
            int x, y;

            do {
                x = random.nextInt(gameWidth);
                y = random.nextInt(gameHeight);
            } while (map[x][y] == 1 || snake1.getBody().contains(new Point(x, y)) ||
                    (twoPlayers && snake2.getBody().contains(new Point(x, y))));

            food = new Point(x, y);
        }

        public void setPaused(boolean paused) {
            if (timer != null) {
                if (paused) {
                    timer.stop();
                } else {
                    timer.start();
                }
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            if (!gameStarted) {
                drawWelcomeScreen(g);
                return;
            }

            // 绘制地图
            for (int x = 0; x < gameWidth; x++) {
                for (int y = 0; y < gameHeight; y++) {
                    if (map[x][y] == 1) {
                        g.setColor(new Color(70, 70, 70));
                        g.fillRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
                        g.setColor(Color.DARK_GRAY);
                        g.drawRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
                    }
                }
            }

            // 绘制食物
            if (food != null) {
                g.setColor(Color.RED);
                g.fillOval(food.x * TILE_SIZE, food.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
            }

            // 绘制蛇
            drawSnake(g, snake1, new Color(50, 180, 50), new Color(30, 120, 30));
            if (twoPlayers) {
                drawSnake(g, snake2, new Color(50, 50, 180), new Color(30, 30, 120));
            }

            // 绘制分数
            g.setColor(Color.WHITE);
            g.setFont(panelFont.deriveFont(Font.BOLD, 16));
            g.drawString("玩家1: " + score1, 10, 20);
            if (twoPlayers) {
                g.drawString("玩家2: " + score2, getWidth() - 100, 20);
            }

            // 游戏结束画面
            if (gameOver) {
                g.setColor(new Color(0, 0, 0, 180));
                g.fillRect(0, 0, getWidth(), getHeight());

                g.setColor(Color.WHITE);
                g.setFont(panelFont.deriveFont(Font.BOLD, 30));

                String gameOverMsg;
                if (twoPlayers) {
                    if (snake1 != null && snake2 == null) {
                        gameOverMsg = "玩家1获胜!";
                    } else if (snake2 != null && snake1 == null) {
                        gameOverMsg = "玩家2获胜!";
                    } else {
                        gameOverMsg = "平局!";
                    }
                } else {
                    gameOverMsg = "游戏结束! 得分: " + score1;
                }

                FontMetrics metrics = g.getFontMetrics();
                int msgWidth = metrics.stringWidth(gameOverMsg);
                g.drawString(gameOverMsg, (getWidth() - msgWidth) / 2, getHeight() / 2 - 30);

                g.setFont(panelFont.deriveFont(Font.PLAIN, 16));
                String restartMsg = "按Enter键重新开始";
                int restartWidth = metrics.stringWidth(restartMsg);
                g.drawString(restartMsg, (getWidth() - restartWidth) / 2, getHeight() / 2 + 20);
            }

            // 暂停状态
            if (isPaused) {
                g.setColor(new Color(0, 0, 0, 180));
                g.fillRect(0, 0, getWidth(), getHeight());

                g.setColor(Color.WHITE);
                g.setFont(panelFont.deriveFont(Font.BOLD, 30));

                String pauseMsg = "游戏暂停";
                FontMetrics metrics = g.getFontMetrics();
                int msgWidth = metrics.stringWidth(pauseMsg);
                g.drawString(pauseMsg, (getWidth() - msgWidth) / 2, getHeight() / 2);
            }
        }

        private void drawWelcomeScreen(Graphics g) {
            g.setColor(new Color(30, 30, 30));
            g.fillRect(0, 0, getWidth(), getHeight());

            g.setColor(Color.WHITE);
            g.setFont(panelFont.deriveFont(Font.BOLD, 36));

            String title = "贪吃蛇游戏";
            FontMetrics metrics = g.getFontMetrics();
            int titleWidth = metrics.stringWidth(title);
            g.drawString(title, (getWidth() - titleWidth) / 2, getHeight() / 3);

            g.setFont(panelFont.deriveFont(Font.PLAIN, 18));
            String instruction = "请从菜单选择游戏设置并开始游戏";
            int instrWidth = metrics.stringWidth(instruction);
            g.drawString(instruction, (getWidth() - instrWidth) / 2, getHeight() / 2);
        }

        private void drawSnake(Graphics g, Snake snake, Color headColor, Color bodyColor) {
            if (snake == null) return;

            List<Point> body = snake.getBody();
            for (int i = 0; i < body.size(); i++) {
                Point p = body.get(i);
                if (i == 0) {
                    g.setColor(headColor);
                } else {
                    g.setColor(bodyColor);
                }
                g.fillRect(p.x * TILE_SIZE, p.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);

                g.setColor(Color.BLACK);
                g.drawRect(p.x * TILE_SIZE, p.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (gameOver || isPaused) return;

            // 移动蛇
            snake1.move();
            if (twoPlayers && snake2 != null) {
                snake2.move();
            }

            // 检查碰撞
            checkCollisions();

            // 检查是否吃到食物
            checkFood();

            repaint();
        }

        private void checkCollisions() {
            // 检查蛇1
            Point head1 = snake1.getHead();
            // 撞墙
            if (head1.x < 0 || head1.x >= gameWidth || head1.y < 0 || head1.y >= gameHeight || map[head1.x][head1.y] == 1) {
                snake1 = null;
            }
            // 撞自己
            else if (snake1.getBody().subList(1, snake1.getBody().size()).contains(head1)) {
                snake1 = null;
            }
            // 双人模式下撞对方
            else if (twoPlayers && snake2 != null && snake2.getBody().contains(head1)) {
                snake1 = null;
            }

            // 检查蛇2(双人模式)
            if (twoPlayers && snake2 != null) {
                Point head2 = snake2.getHead();
                // 撞墙
                if (head2.x < 0 || head2.x >= gameWidth || head2.y < 0 || head2.y >= gameHeight || map[head2.x][head2.y] == 1) {
                    snake2 = null;
                }
                // 撞自己
                else if (snake2.getBody().subList(1, snake2.getBody().size()).contains(head2)) {
                    snake2 = null;
                }
                // 撞对方
                else if (snake1 != null && snake1.getBody().contains(head2)) {
                    snake2 = null;
                }
            }

            // 检查游戏是否结束
            if (snake1 == null && (!twoPlayers || snake2 == null)) {
                gameOver = true;
                timer.stop();
            } else if (twoPlayers && ((snake1 == null) != (snake2 == null))) {
                gameOver = true;
                timer.stop();
            }
        }

        private void checkFood() {
            if (snake1 != null && snake1.getHead().equals(food)) {
                snake1.grow();
                score1 += 10;
                spawnFood();
            }

            if (twoPlayers && snake2 != null && snake2.getHead().equals(food)) {
                snake2.grow();
                score2 += 10;
                spawnFood();
            }
        }
    }

    private enum Direction {
        UP, DOWN, LEFT, RIGHT
    }

    private class Snake {
        private List<Point> body;
        private Direction direction;
        private boolean shouldGrow = false;

        public Snake(int startX, int startY, Direction startDirection) {
            body = new LinkedList<>();
            body.add(new Point(startX, startY));
            direction = startDirection;
        }

        public void move() {
            Point head = getHead();
            Point newHead = new Point(head);

            switch (direction) {
                case UP:
                    newHead.y--;
                    break;
                case DOWN:
                    newHead.y++;
                    break;
                case LEFT:
                    newHead.x--;
                    break;
                case RIGHT:
                    newHead.x++;
                    break;
            }

            body.add(0, newHead);

            if (shouldGrow) {
                shouldGrow = false;
            } else {
                body.remove(body.size() - 1);
            }
        }

        public void grow() {
            shouldGrow = true;
        }

        public Point getHead() {
            return body.get(0);
        }

        public List<Point> getBody() {
            return body;
        }

        public Direction getDirection() {
            return direction;
        }

        public void setDirection(Direction direction) {
            this.direction = direction;
        }
    }

    private class GameMenu extends JMenuBar {
        private JComboBox<String> difficultyCombo;
        private JComboBox<String> modeCombo;
        private JComboBox<String> mapCombo;

        public GameMenu(SnakeGame game) {
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            // 游戏菜单
            JMenu gameMenu = createMenu("游戏", game);
            add(gameMenu);
            add(Box.createVerticalStrut(10));

            // 设置菜单
            JMenu settingsMenu = createSettingsMenu(game);
            add(settingsMenu);
            add(Box.createVerticalStrut(10));

            // 帮助菜单
            JMenu helpMenu = createHelpMenu();
            add(helpMenu);
        }

        private JMenu createMenu(String title, SnakeGame game) {
            JMenu menu = new JMenu(title);
            menu.setFont(uiFont);

            JMenuItem newGameItem = new JMenuItem("新游戏");
            newGameItem.setFont(uiFont);
            newGameItem.addActionListener(e -> showNewGameDialog(game));
            menu.add(newGameItem);

            JMenuItem pauseItem = new JMenuItem("暂停(P)");
            pauseItem.setFont(uiFont);
            pauseItem.addActionListener(e -> game.togglePause());
            menu.add(pauseItem);

            JMenuItem exitItem = new JMenuItem("退出");
            exitItem.setFont(uiFont);
            exitItem.addActionListener(e -> System.exit(0));
            menu.add(exitItem);

            return menu;
        }

        private JMenu createSettingsMenu(SnakeGame game) {
            JMenu settingsMenu = new JMenu("设置");
            settingsMenu.setFont(uiFont);

            // 难度菜单
            JMenu difficultyMenu = createDifficultyMenu(game);
            settingsMenu.add(difficultyMenu);

            // 地图菜单
            JMenu mapMenu = createMapMenu();
            settingsMenu.add(mapMenu);

            // 模式菜单
            JMenu modeMenu = createModeMenu();
            settingsMenu.add(modeMenu);

            return settingsMenu;
        }

        private JMenu createDifficultyMenu(SnakeGame game) {
            JMenu difficultyMenu = new JMenu("难度");
            difficultyMenu.setFont(uiFont);
            ButtonGroup difficultyGroup = new ButtonGroup();

            JRadioButtonMenuItem easyItem = new JRadioButtonMenuItem("简单");
            easyItem.setFont(uiFont);
            easyItem.setSelected(true);
            easyItem.addActionListener(e -> game.speed = 200);
            difficultyMenu.add(easyItem);
            difficultyGroup.add(easyItem);

            JRadioButtonMenuItem mediumItem = new JRadioButtonMenuItem("中等");
            mediumItem.setFont(uiFont);
            mediumItem.addActionListener(e -> game.speed = 150);
            difficultyMenu.add(mediumItem);
            difficultyGroup.add(mediumItem);

            JRadioButtonMenuItem hardItem = new JRadioButtonMenuItem("困难");
            hardItem.setFont(uiFont);
            hardItem.addActionListener(e -> game.speed = 100);
            difficultyMenu.add(hardItem);
            difficultyGroup.add(hardItem);

            return difficultyMenu;
        }

        private JMenu createMapMenu() {
            JMenu mapMenu = new JMenu("地图");
            mapMenu.setFont(uiFont);
            ButtonGroup mapGroup = new ButtonGroup();

            JRadioButtonMenuItem emptyMapItem = new JRadioButtonMenuItem("空白");
            emptyMapItem.setFont(uiFont);
            emptyMapItem.setSelected(true);
            mapMenu.add(emptyMapItem);
            mapGroup.add(emptyMapItem);

            JRadioButtonMenuItem borderedMapItem = new JRadioButtonMenuItem("边框");
            borderedMapItem.setFont(uiFont);
            mapMenu.add(borderedMapItem);
            mapGroup.add(borderedMapItem);

            JRadioButtonMenuItem mazeMapItem = new JRadioButtonMenuItem("迷宫");
            mazeMapItem.setFont(uiFont);
            mapMenu.add(mazeMapItem);
            mapGroup.add(mazeMapItem);

            return mapMenu;
        }

        private JMenu createModeMenu() {
            JMenu modeMenu = new JMenu("模式");
            modeMenu.setFont(uiFont);
            ButtonGroup modeGroup = new ButtonGroup();

            JRadioButtonMenuItem singlePlayerItem = new JRadioButtonMenuItem("单人");
            singlePlayerItem.setFont(uiFont);
            singlePlayerItem.setSelected(true);
            modeMenu.add(singlePlayerItem);
            modeGroup.add(singlePlayerItem);

            JRadioButtonMenuItem twoPlayersItem = new JRadioButtonMenuItem("双人");
            twoPlayersItem.setFont(uiFont);
            modeMenu.add(twoPlayersItem);
            modeGroup.add(twoPlayersItem);

            return modeMenu;
        }

        private JMenu createHelpMenu() {
            JMenu helpMenu = new JMenu("帮助");
            helpMenu.setFont(uiFont);

            JMenuItem controlsItem = new JMenuItem("控制说明");
            controlsItem.setFont(uiFont);
            controlsItem.addActionListener(e -> showControlsDialog());
            helpMenu.add(controlsItem);

            JMenuItem aboutItem = new JMenuItem("关于");
            aboutItem.setFont(uiFont);
            aboutItem.addActionListener(e -> showAboutDialog());
            helpMenu.add(aboutItem);

            return helpMenu;
        }

        private void showNewGameDialog(SnakeGame game) {
            JDialog dialog = new JDialog(game, "新游戏设置", true);
            dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
            dialog.setSize(300, 300);

            // 统一设置字体
            dialog.setFont(uiFont);

            // 地图大小
            JPanel sizePanel = new JPanel(new GridLayout(2, 2, 10, 10));
            JLabel widthLabel = new JLabel("宽度:");
            widthLabel.setFont(uiFont);
            sizePanel.add(widthLabel);
            JTextField widthField = new JTextField(String.valueOf(game.gameWidth));
            widthField.setFont(uiFont);
            sizePanel.add(widthField);
            JLabel heightLabel = new JLabel("高度:");
            heightLabel.setFont(uiFont);
            sizePanel.add(heightLabel);
            JTextField heightField = new JTextField(String.valueOf(game.gameHeight));
            heightField.setFont(uiFont);
            sizePanel.add(heightField);
            dialog.add(sizePanel);
            dialog.add(Box.createVerticalStrut(10));

            // 难度选择
            JPanel difficultyPanel = new JPanel();
            JLabel difficultyLabel = new JLabel("难度:");
            difficultyLabel.setFont(uiFont);
            difficultyPanel.add(difficultyLabel);
            difficultyCombo = new JComboBox<>(new String[]{"简单", "中等", "困难"});
            difficultyCombo.setFont(uiFont);
            difficultyCombo.setSelectedIndex(1); // 默认中等
            difficultyPanel.add(difficultyCombo);
            dialog.add(difficultyPanel);
            dialog.add(Box.createVerticalStrut(10));

            // 模式选择
            JPanel modePanel = new JPanel();
            JLabel modeLabel = new JLabel("模式:");
            modeLabel.setFont(uiFont);
            modePanel.add(modeLabel);
            modeCombo = new JComboBox<>(new String[]{"单人", "双人"});
            modeCombo.setFont(uiFont);
            modePanel.add(modeCombo);
            dialog.add(modePanel);
            dialog.add(Box.createVerticalStrut(10));

            // 地图类型
            JPanel mapPanel = new JPanel();
            JLabel mapLabel = new JLabel("地图类型:");
            mapLabel.setFont(uiFont);
            mapPanel.add(mapLabel);
            mapCombo = new JComboBox<>(new String[]{"空白", "边框", "迷宫"});
            mapCombo.setFont(uiFont);
            mapPanel.add(mapCombo);
            dialog.add(mapPanel);
            dialog.add(Box.createVerticalStrut(10));

            // 按钮
            JPanel buttonPanel = new JPanel();
            JButton startButton = new JButton("开始游戏");
            startButton.setFont(uiFont);
            startButton.addActionListener(e -> {
                try {
                    int width = Integer.parseInt(widthField.getText());
                    int height = Integer.parseInt(heightField.getText());
                    int speed = 150;
                    switch (difficultyCombo.getSelectedIndex()) {
                        case 0: speed = 200; break;
                        case 1: speed = 150; break;
                        case 2: speed = 100; break;
                    }
                    boolean twoPlayers = modeCombo.getSelectedIndex() == 1;
                    int mapType = mapCombo.getSelectedIndex();

                    if (width < 10 || width > 30 || height < 10 || height > 20) {
                        JOptionPane.showMessageDialog(dialog, "宽度应在10 - 30之间，高度应在10 - 20之间", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    game.startNewGame(width, height, speed, twoPlayers, mapType);
                    dialog.dispose();
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
                }
            });
            buttonPanel.add(startButton);

            JButton cancelButton = new JButton("取消");
            cancelButton.setFont(uiFont);
            cancelButton.addActionListener(e -> dialog.dispose());
            buttonPanel.add(cancelButton);
            dialog.add(buttonPanel);

            dialog.pack();
            dialog.setLocationRelativeTo(game);
            dialog.setVisible(true);
        }

        private void showControlsDialog() {
            String message = "单人模式控制:\n"
                    + "W/↑ - 向上\n"
                    + "S/↓ - 向下\n"
                    + "A/← - 向左\n"
                    + "D/→ - 向右\n\n"
                    + "双人模式控制:\n"
                    + "玩家1: W/A/S/D 或 方向键\n"
                    + "玩家2: I/J/K/L\n\n"
                    + "P - 暂停游戏\n"
                    + "Enter - 重新开始游戏";
            JLabel messageLabel = new JLabel("<html>" + message.replace("\n", "<br>") + "</html>");
            messageLabel.setFont(uiFont);
            JOptionPane.showMessageDialog(null, messageLabel, "控制说明", JOptionPane.INFORMATION_MESSAGE);
        }

        private void showAboutDialog() {
            String message = """
                    贪吃蛇游戏
                    Java Swing 实现
                    版本 1.0
                    
                    功能:
                    - 单人/双人模式
                    - 多种难度选择
                    - 不同地图选择
                    - 分数记录""";
            JLabel messageLabel = new JLabel("<html>" + message.replace("\n", "<br>") + "</html>");
            messageLabel.setFont(uiFont);
            JOptionPane.showMessageDialog(null, messageLabel, "关于", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SnakeGame game = new SnakeGame();
            game.setVisible(true);
        });
    }
}